#
# LianHaidong <lianhaidong@gmail.com>
#


ifeq ($(OS), Linux)
THIS_DIR = $(shell pwd)
else  #Windows
THIS_DIR = $(shell cd)
endif

PPAD := $(PAD)
PAD := $(PAD)--

GEN_DEP = $(CC) $(CFLAGS) -MM

TARGET = sub_$(notdir $(THIS_DIR)).o 

DEPS = $(sort $(OBJS-y:.o=.d))

ASM_DEPS = $(sort $(ASM_OBJS-y:.o=.d))

SUB_OBJS := $(foreach n, $(SUB_DIRS), $(n)/sub_$(n).o)
STATIC_LIBS := $(foreach n, $(STATIC_DIRS), lib$(n).a)
SHARE_LIBS := $(foreach n, $(SHARE_DIRS), lib$(n).so)

all : $(DEPS) $(ASM_DEPS) $(SUB_DIRS) $(TARGET) 


$(DEPS) : %.d : %.c
	@echo -e "$(DEP_COLOR)$(PAD)> GEN_DEP $@$(DEFAULT_COLOR)"
	$(GEN_DEP) $< >$@

$(ASM_DEPS) : %.d : %.S
	$(GEN_DEP) $< >$@


$(TARGET) : $(OBJS-y) $(ASM_OBJS-y) $(SUB_OBJS)
	@echo -e "$(LD_COLOR)$(PAD)> LD $@$(DEFAULT_COLOR)"
	$(LD) $(LD_FLAGS) $(LOCAL_LD_FLAGS) -r $^ -o $@

$(sort $(OBJS-y)) : %.o : %.c
	@echo -e "$(CC_COLOR)$(PAD)> CC $@$(DEFAULT_COLOR)"
	$(CC) $(CFLAGS) $(LOCAL_CFLAGS) -c $< -o $@

$(sort $(ASM_OBJS-y)) : %.o : %.S
	$(CC) $(CFLAGS) -c $< -o $@


$(SUB_DIRS) :
	@echo -e "$(DIR_COLOR)$(PPAD)Enter $(CURDIR)/$@$(DEFAULT_COLOR)"
	$(MAKE) -C $@
	@echo -e "$(DIR_COLOR)$(PPAD)Leave $(CURDIR)/$@$(DEFAULT_COLOR)"

#$(STATIC_LIB_DIRS) :
#	$(MAKE) -C $@
#$(SHARE_LIB_DIRS) :
#	$(MAKE) -C $@


_DEPS = $(wildcard $(DEPS))

-include $(_DEPS)

export TOP_DIR INCLUDE_DIR CROSS_COMPILE CC AS LD OBJDUMP OBJCOPY CFLAGS LD_FLAGS PAD

.PHONY : $(SUB_DIRS) 

.PHONY : $(PHONY_DIRS)
PHONY_DIRS = $(SUB_DIRS:=.DIR) 


clean : $(PHONY_DIRS)
	-rm -rf $(DEPS) $(sort $(OBJS-y)) $(sort $(ASM_OBJS-y)) $(TARGET)

clean_svn:
	-rm -rf .svn


$(PHONY_DIRS) :
	@echo "--------- CLEAN $(@:.DIR=)"
	$(MAKE) clean -C $(@:.DIR=)









